/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;

import scheduler.databean.Course;
import scheduler.databean.Schedule;
import scheduler.databean.User;
import scheduler.formbean.LoginForm;
import scheduler.model.CourseDao;
import scheduler.model.Model;
import scheduler.model.ScheduleDao;

public class SavedSchedulesAction extends Action {
	private ScheduleDao scheduleDao;
	private CourseDao courseDao;

	public SavedSchedulesAction(Model model) {
		scheduleDao = model.getScheduleDao();
		courseDao = model.getCourseDao();
	}

	public String getName() { return "saved-schedules.do"; }
	
	public String parseSectionId(String sectionId) {
		return sectionId.substring(0, 2) + "-" + sectionId.substring(2, 5) + " " + sectionId.substring(5);
	}
	
    public String perform(HttpServletRequest request) {
		// Must be logged in for this one
    	HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
		if (user == null) {
			LoginForm loginForm = new LoginForm();
			loginForm.setRedirect("/saved-schedules.do");
	        request.setAttribute("form",loginForm);
			return "login.jsp";
		}

    	String userName = user.getUserName();
    	
        try {
        	String page = "<div id=\"savedSchedules\">\n";
        	int numSchedule = user.getNumSchedule();
        	for (int i = 0; i < numSchedule; i++) {
        		Schedule[] temp = scheduleDao.getSchedule(userName,i);
        		int units = 0;
        		if (temp.length > 0) {
		        	page += "<a class=\"schedule\" href=\"schedule.do?scheduleID=" + i + "\">" + temp[0].getSemester() + " " + temp[0].getYear() + "</a>\n" +
		        			"<ul>\n";
	        		for (int j = 0; j < temp.length; j++) {
	        			Course tempCourse = courseDao.lookup(temp[j].getCourseId());
	        			units += tempCourse.getUnit();
	        			page += "<li>" + parseSectionId(temp[j].getSectionId()) + " : " + "<a class=\"description\" target=\"_blank\" href=\"course.do?course=" + tempCourse.getId() + "\" title=\"Click to view a description for this course\" onclick=\"window.open(this.href,'new_window','width=600,height=600,scrollbars=yes');return false;\">" + tempCourse.getCourseName() + "</a> (" + tempCourse.getUnit() + " units)</li>\n";
	        		}
	        		page += "<li class=\"unit\">Total " + units + " units</li>\n" +
	        				"</ul>\n";
        		}
        	}
        	
        	page += "</div>\n";
        	
        	request.setAttribute("page", page);
        	
		} catch (DAOException e) {
        	e.printStackTrace();
        	request.setAttribute("dbError",e.getMessage());
        	return "db-error.jsp";
		}

    	return "saved-schedules.jsp";
    }
}
